package com.wedo.mall.activity.agent;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.e.library.activity.EActivity;
import com.e.library.http.EApi;
import com.e.library.http.EObserver;
import com.e.library.http.EResponse;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.wedo.mall.R;
import com.wedo.mall.activity.chat.ConsultActivity;
import com.wedo.mall.activity.comment.CommentActivity;
import com.wedo.mall.activity.login.WLogin;
import com.wedo.mall.adapter.FavourableAdapter;
import com.wedo.mall.dialog.ConsultDialog;
import com.wedo.mall.dialog.ShareDialog;
import com.wedo.mall.entity.Agent;
import com.wedo.mall.entity.AgentDetail;
import com.wedo.mall.entity.Goods;
import com.wedo.mall.ptr.Pull2Refresh;
import com.wedo.mall.util.WUrl;
import com.wedo.mall.util.WUtils;
import com.wedo.mall.widget.StarView;

import butterknife.BindString;
import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;

/**
  * 店铺详情
 * Created by e on 2017/7/16.
 */

public class AgentDetailActivity extends EActivity {

    public static final String EXTRA_AGENT = "agent";
    public static final int REQ_COLLECT = 1;

    public static void toDetail(EActivity activity,String id){
        Bundle bundle = new Bundle();
        bundle.putString(EXTRA_AGENT,id);
        activity.toActivity(AgentDetailActivity.class,bundle);
    }

    private ImageView iv_img;
    private StarView sv_star;
    private TextView tv_name;
    private TextView tv_comment;
    private TextView tv_brow;
    private TextView tv_address;
    private TextView tv_sort_sale;
    private TextView tv_sort_price;

    @BindView(R.id.tv_empty) TextView tv_empty;
    @BindView(R.id.rv_list) XRecyclerView rv_list;
    @BindView(R.id.tv_collection) TextView tv_collection;

    @BindString(R.string.agent_comment) String agent_comment;
    @BindString(R.string.agent_review) String agent_review;
    @BindString(R.string.agent_address) String agent_address;

    private Pull2Refresh<Goods> ptr;
    private String id;
    private Agent agent;
    private AgentDetail detail;
    private SparseArray<String> sorts = new SparseArray<>(2);

    @Override
    protected int layout() {
        return R.layout.activity_agent_detail;
    }

    @Override
    protected void onActivityCreated(Bundle state) {

        id = getIntent().getStringExtra(EXTRA_AGENT);

        rv_list.setHasFixedSize(true);
        rv_list.setLayoutManager(new GridLayoutManager(this,2));
        ptr = new Pull2Refresh<>();

        //GoodsAdapter adapter = new GoodsAdapter(this,null);
        FavourableAdapter adapter = new FavourableAdapter(this,null);
        adapter.listener(this);

        View header = LayoutInflater.from(this).inflate(R.layout.header_agent_detail,null);
        iv_img = (ImageView) header.findViewById(R.id.iv_img);
        sv_star = (StarView) header.findViewById(R.id.sv_star);
        tv_name = (TextView) header.findViewById(R.id.tv_name);
        tv_brow = (TextView) header.findViewById(R.id.tv_brow);
        tv_comment = (TextView) header.findViewById(R.id.tv_comment);
        tv_address = (TextView) header.findViewById(R.id.tv_address);
        tv_sort_sale = (TextView) header.findViewById(R.id.tv_sort_sale);
        tv_sort_price = (TextView) header.findViewById(R.id.tv_sort_price);

        tv_comment.setOnClickListener(listener);
        tv_address.setOnClickListener(listener);
        header.findViewById(R.id.tv_more).setOnClickListener(listener);
        header.findViewById(R.id.tv_sort_all).setOnClickListener(listener);
        header.findViewById(R.id.tv_sort_sale).setOnClickListener(listener);
        header.findViewById(R.id.tv_sort_price).setOnClickListener(listener);

        detail(id);

        sorts.put(R.id.tv_sort_sale,"sale_sort");
        sorts.put(R.id.tv_sort_price,"price_sort");

        ptr.widget(rv_list).adapter(adapter).url(EApi.AGENT_GOODS).param("id",id).clazz(Goods.class).emptyWidget(tv_empty).done();
        rv_list.addHeaderView(header);
    }

    private void detail(String id){
        loading();
        Observable<EResponse> observable = api().agentDetail(id);
        observer(observable, new EObserver() {
            @Override
            public void successful(EResponse response) {
                dismiss();
                display(response);
            }

            @Override
            public void failure(String msg) {
                dismiss(msg);
            }

        });
    }


    private void display(EResponse response){
        detail = response.object("list",AgentDetail.class);
        agent = detail.agentDetail;
        if(agent == null) {
            toast(R.string.agent_no_exist);
            defaultFinish();
            return;
        }

        int comment = detail.commentCount;
        int brow = detail.browingCount;
        int is_collect = detail.is_collect;
        onCollectionChanged(is_collect == 1);

        tv_comment.setText(String.format(agent_comment,comment));
        tv_brow.setText(String.format(agent_review,brow));

        sv_star.star(agent.star);
        tv_name.setText(agent.agent_name);

        tv_address.setText(String.format(agent_address,agent.address));
        String url = WUrl.url(agent.logo);
        Glide.with(this).load(url).placeholder(R.drawable.place_holder_agent).error(R.drawable.place_holder_agent).diskCacheStrategy(DiskCacheStrategy.ALL).into(iv_img);
    }

    private View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()){
                case R.id.tv_more:
                    Bundle bundle = new Bundle();
                    bundle.putParcelable(EXTRA_AGENT,agent);
                    toActivityForResult(AgentIntroActivity.class,bundle,REQ_COLLECT);

                    break;
                case R.id.tv_sort_all:
                    /**全部商品*/
                    tv_sort_sale.setSelected(false);
                    tv_sort_price.setSelected(false);
                    ptr.removeParam("sale_sort").removeParam("price_sort").refresh();
                    break;
                case R.id.tv_sort_sale:
                case R.id.tv_sort_price:
                    int viewId = v.getId();
                    String key = sorts.get(viewId);
                    v.setSelected(!v.isSelected());
                    /**0表示升序，1表示降序*/
                    String value = v.isSelected()?"0":"1";
                    ptr.param(key,value).refresh();
                    break;
                case R.id.tv_comment:
                    CommentActivity.toAgentComment(AgentDetailActivity.this,AgentDetailActivity.this.id);
                    break;
                case R.id.tv_address:
                    navigation();
                    break;
            }

        }
    };

    private void navigation(){
        if (agent == null){
            return;
        }
        if (TextUtils.isEmpty(agent.latitude) || TextUtils.isEmpty(agent.longitude)){
            toast(R.string.ease_map_geo_invalid);
            return;
        }

        double lat = WUtils.toDouble(agent.latitude);
        double lng = WUtils.toDouble(agent.longitude);
        if (lat == 0 || lng == 0){
            toast(R.string.ease_map_geo_invalid);
            return;
        }

        if (WUtils.isGoogleMapsInstalled(this)){
            /**app导航*/
            StringBuffer nav = new StringBuffer("google.navigation:q=").append(lat).append(",").append(lng).append("&mode=d");
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(nav.toString()));
            intent.setPackage("com.google.android.apps.maps");
            startActivity(intent);
        }else {
            /**web导航*/
            StringBuffer nav = new StringBuffer("http://ditu.google.cn/maps?hl=zh&mrt=loc&q=").append(lat).append(",").append(lng);
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(nav.toString()));
            startActivity(intent);
        }

    }

    private void onCollectionChanged(boolean is_collect){
        if(is_collect) {
            tv_collection.setSelected(true);
            tv_collection.setText(R.string.agent_del_collect);
        }else {
            tv_collection.setSelected(false);
            tv_collection.setText(R.string.agent_add_collect);
        }

    }

    @OnClick(R.id.iv_backward)
    protected void onBackwardClick(){
        defaultFinish();
    }

    @OnClick(R.id.iv_share)
    protected void onShareClick(){
        ShareDialog.with(this).agent(agent).show();
    }

    @OnClick(R.id.iv_search)
    protected void onSearchClick(){
        Intent intent = new Intent(AgentDetailActivity.this,AgentSearchGoodsActivity.class);
        intent.putExtras(getIntent());
        toActivity(intent);
    }

    @OnClick(R.id.ll_consult)
    protected void onConsultClick(){
        ConsultDialog dialog = ConsultDialog.with(this);
        dialog.listener = new ConsultDialog.OnConsultListener() {
            @Override
            public void onConsult(int type) {
                if(type == ConsultDialog.CONSULT_PHONE) {
                    WUtils.requestPhoneCall(AgentDetailActivity.this,agent.agent_phone);
                }else {
                    //环信聊天
                    toConsultActivity();
                }
            }
        };

        dialog.show();
    }

    /**环信聊天*/
    private void toConsultActivity(){
        if(!WLogin.isLogged(this)) {
            return;
        }
        ConsultActivity.toConsult(this,agent);
    }

    @OnClick(R.id.tv_collection)
    protected void onCollectionClick(){
        if (tv_collection.isSelected()){
            delCollect();
        }else {
            toCollect();
        }
    }

    private void toCollect(){
        if(!WLogin.isLogged(this)) {
            return;
        }

        String id = agent.id;
        String type = "1";

        loading();
        Observable<EResponse> observable = api().collect(id,type);
        observer(observable, new EObserver() {
            @Override
            public void successful(EResponse response) {
                dismiss();
                detail.collect_id = response.string("collect_id");
                onCollectionChanged(true);
            }

            @Override
            public void failure(String msg) {
                dismiss(msg);
            }
        });
    }

    private void delCollect(){
        loading();
        Observable<EResponse> observable = api().delCollect(detail.collect_id);
        observer(observable, new EObserver() {
            @Override
            public void successful(EResponse response) {
                dismiss();
                onCollectionChanged(false);
            }

            @Override
            public void failure(String msg) {
                dismiss(msg);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQ_COLLECT && resultCode == RESULT_OK) {
            detail.collect_id = data.getStringExtra("collect_id");
            boolean is_collect = data.getBooleanExtra("is_collect", false);
            onCollectionChanged(is_collect);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == WUtils.REQ_PHONE_CALL) {
            if(grantResults.length >0) {
                WUtils.phoneCall(AgentDetailActivity.this,agent.agent_phone);
            }
        }
    }
}
